<template>
  <header id="admin-header">
    <div class="header-top container-fluid flex-between">
      <div class="header-top-l flex-align-items">
        <div class="corp">
          <div class="flex-align-items">
            <img
              v-if="companyInfo.bgImage && !imgLoad"
              @error="imgErrored"
              @load="imgLoad = false"
              :src="companyInfo.bgImage"
              alt="Maadtech DSP logo"
              ref="bgImage"
            />

            <a-button
              class="dark-b-999"
              style="margin-right: 5px"
              v-show="imgLoad"
              size="small"
              shape="circle"
              :loading="iconLoading"
              icon="reload"
              @click="againLoad"
            />

            <!-- 页头 -->
            <strong>{{companyInfo.subTitle}}</strong>&nbsp;
          </div>
        </div>
        <div class="bar" v-if="isMobile">
          <a-button @click="showMenuClick">
            <a-icon type="bars" />
          </a-button>
        </div>
      </div>
      <div class="header-top-r flex-align-items" v-if="!isMobile||showMenu">
        <div class="select-user" v-if="isAdmin">
          <a-select :value="userByCompanyDefault" style="width: 100%;" showSearch>
            <a-select-option
              v-for="(user, key) in userByCompanys"
              :key="key"
              :value="user.value"
              @click="changeUserByCompany(user.value, user.id)"
            >{{user.value}}</a-select-option>
          </a-select>
        </div>

        <div :class="{'no-border': showTemplateBelowIcons}" class="header-tools flex-align-items">
          <!-- 用户选项 -->
          <a-dropdown>
            <a
              class="ant-dropdown-link flex-align-items"
              :class="{'keep-bgcolor': showUserList}"
              @click="tabToggle('user')"
            >
              <span class="iconfont icon-user"></span>
            </a>
            <a-menu slot="overlay" v-if="!isMobile">
              <a-menu-item>
                <router-link to="/bidder/profile">
                  <a-icon type="user" />
                  <span class="dropdown-text" v-text="$t('pro.public.header.MyProfile')"></span>
                </router-link>
              </a-menu-item>

              <!-- 操作指南 -->
              <!-- <a-menu-item @click="modalConfig.visible = true">
                                <a-icon type="customer-service"/>
                                <span v-text="$t('pro.public.header.guide')"></span>
              </a-menu-item>-->
              <!--<a-menu-item>
                                <a href="" target="_blank">
                                    <a-icon type="read"/>
                                    <span class="dropdown-text" v-text="$t('pro.public.header.manual')"></span>
                                </a>
              </a-menu-item>-->
              <a-menu-item @click="logout">
                <a-icon type="logout" />
                <span v-text="$t('pro.public.header.LogOut')"></span>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          <a-dropdown>
            <a
              class="ant-dropdown-link flex-align-items"
              :class="{'keep-bgcolor': showLanguageSelect}"
              @click="tabToggle('language')"
            >
              <span class="iconfont icon-globe"></span>
            </a>
            <a-menu slot="overlay" v-if="!isMobile">
              <a-menu-item @click="setLanguage('en')">
                <span>English</span>
              </a-menu-item>
              <a-menu-item @click="setLanguage('cn')">
                <span>中文(简体)</span>
              </a-menu-item>
              <a-menu-item @click="setLanguage('cn_TW')">
                <span>中文(繁體)</span>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
        <template v-if="showTemplateBelowIcons">
          <div class="template-below-icons">
            <!-- 移动端语言选项 -->
            <div
              v-if="showLanguageSelect"
              class="mobile-language-select flex-align-items flex-between"
            >
              <label
                v-for="item in ['en','cn','cn_TW']"
                :key="item"
                :for="item"
                :class="{selected: getLanguage == item}"
                @click="setLanguage(item)"
              >{{item == 'en' ? 'English' : item == 'cn' ? '中文(简体)' : '中文(繁體)' }}</label>
            </div>
            <!-- 移动端用户选项 -->
            <ul v-else-if="showUserList" class="mobile-profile-list">
              <li>
                <router-link to="/bidder/profile">{{ $t('pro.public.header.MyProfile') }}</router-link>
              </li>
              <!-- 操作指南 -->
              <!-- <li><a href="#" @click="modalConfig.visible = true"
              v-text="$t('pro.public.header.guide')"></a></li>-->

              <!-- <li><a href="https://doc.surgemobi.com/" target="_blank">{{ $t('pro.public.header.manual')
              }}</a></li>-->
              <li>
                <a href="#" @click="logout" v-text="$t('pro.public.header.LogOut')">Log Out</a>
              </li>
            </ul>
            <!-- 移动端消息框 -->
            <!-- <msg-box v-else :isMobile="isMobile" :msgData="msg" slot="overlay"></msg-box> -->
          </div>
        </template>
      </div>
    </div>
    <div class="header-botom">
      <nav class="header-menu container-fluid flex-between" v-if="!isMobile||showMenu">
        <a-menu
          :mode="mode"
          :theme="theme"
          :openKeys.sync="openKeys"
          :selectedKeys="selectedKey"
          v-model="current"
          :inlineIndent="10"
        >
          <!-- dashboard -->
          <a-menu-item key="/dashboard">
            <router-link to="/dashboard">
              <a-icon type="dashboard" />
              <span v-text="$t('pro.public.header.Dashboard')"></span>
            </router-link>
          </a-menu-item>

          <!-- bidder -->
          <a-sub-menu
            key="bidder"
            @mouseover="bidderAd"
            :class="{ 'submenu-opening': openKeys.includes('bidder'), 'submenu-selected': current[0].includes('bidder'),'new-user-bidder':true }"
          >
            <span slot="title" class="submenu-title-wrapper">
              <a-icon type="appstore" />
              {{ $t('pro.public.header.Campaigns') }}
              <!-- 新用户首次提示创建广告 -->
              <div class="new-user-tips" v-if="newUserFlay">
                <svg
                  t="1570700018050"
                  class="icon"
                  viewBox="0 0 4507 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="51168"
                  width="100"
                  height="48"
                >
                  <path
                    d="M19.272909 593.38752C1245.000909-149.0944 2549.494989-181.28896 3932.714189 496.64c18.96448-54.8864 44.6464-150.81472 76.92288-287.70304a40.96 40.96 0 0 1 75.61216-10.6496l408.53504 729.04704a40.96 40.96 0 0 1-37.64224 60.94848l-837.14048-38.2976a40.96 40.96 0 0 1-25.51808-71.39328c103.50592-93.10208 172.8512-160.5632 208.0768-202.50624C2533.110989 67.33824 1285.428429 63.73376 58.471629 665.1904a40.96 40.96 0 0 1-39.23968-71.80288z"
                    fill="#ffffff"
                    p-id="51169"
                  />
                </svg>

                <div>
                  <a-icon style="font-size: 2rem;color: #E45250" theme="filled" type="fire" />
                  {{ $t('pro.public.newUserTips') }}
                  <a-button type="primary" @click.stop="toNewBidder">{{ $t('pro.public.gotIt') }}</a-button>
                </div>
              </div>
            </span>

            <a-menu-item v-for="(item) in bidderListL" :key="item.key">
              <router-link :to="item.to" v-text="$t(item.text)"></router-link>
            </a-menu-item>

            <!--<a-menu-item key="/bidder/CampaignsRules">
                          <router-link to="/bidder/CampaignsRules" v-text="$t('pro.public.header.ManagementRules')"></router-link>
            </a-menu-item>-->
          </a-sub-menu>

          <!-- reports -->
          <a-sub-menu
            key="reports"
            :class="{
            'submenu-opening': openKeys.includes('reports'),
            'submenu-selected': current[0].includes('reports')
          }"
          >
            <span slot="title" class="submenu-title-wrapper">
              <a-icon type="fund" />
              {{$t('pro.public.header.Reports')}}
            </span>
            <a-menu-item key="/reports">
              <router-link to="/reports/index/0" v-text="$t('pro.public.header.Reports')"></router-link>
            </a-menu-item>
            <a-menu-item key="/reports/alerts">
              <!-- 智能活动 -->
              <router-link to="/reports/alerts" v-text="$t('pro.public.header.CampaignsServe')"></router-link>
            </a-menu-item>
          </a-sub-menu>

          <!-- billing -->
          <a-sub-menu
            key="billing"
            :class="{
            'submenu-opening': openKeys.includes('billing'),
            'submenu-selected': current[0].includes('billing')
          }"
          >
            <span slot="title" class="submenu-title-wrapper">
              <a-icon type="dollar" />
              {{$t('pro.public.header.Billing')}}
            </span>
            <a-menu-item key="/billing/billing">
              <router-link to="/billing/billing" v-text="$t('pro.public.header.Billing')"></router-link>
            </a-menu-item>
            <a-menu-item key="/billing/invoice">
              <router-link to="/billing/invoice" v-text="$t('pro.public.header.Invoicing')"></router-link>
            </a-menu-item>
            <a-menu-item key="/billing/transactionhistory">
              <router-link
                to="/billing/transactionhistory"
                v-text="$t('pro.public.header.TransactionHistory')"
              ></router-link>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>

        <!-- admin -->
        <a-menu
          :mode="mode"
          :theme="theme"
          :openKeys.sync="openKeys"
          :selectedKeys="selectedKey"
          v-model="current"
          :inlineIndent="20"
        >
          <!-- ADMIN -->
          <a-sub-menu
            v-if="isAdmin"
            key="admin"
            :class="{
              'submenu-opening': openKeys.includes('admin'),
              'submenu-selected': current[0].includes('admin')
            }"
          >
            <span slot="title" class="submenu-title-wrapper">
              <span class="iconfont icon-guanliyuan1" style="font-size: 15px;margin-right: 8px;"></span>
              {{ $t('pro.public.header.admin') }}
            </span>
            <a-menu-item v-for="item in adminList" :key="item.link">
              <router-link :to="item.link">{{item.name}}</router-link>
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </nav>
    </div>

    <!-- 指南弹框 -->
    <modal :config="modalConfig" :title="$t('pro.public.header.guide')"></modal>
  </header>
</template>

<script>
import { updateTheme } from "@/assets/JSfunction";
import { MODERATED } from "@/utils/publicStatus";
import { setUserLocale } from "@/api/user";

import modal from "./custom/ImgVoModal";

export default {
  inject: ["reload"],
  data() {
    let path = this.$route.path || this.$route.fullPath;
    return {
      imgLoad: false,
      iconLoading: false,
      current: [path],
      openKeys: [],
      selectedKey: [],
      screenWidth:
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth,
      showMenu: true,
      showLanguageSelect: false,
      showUserList: false,
      bangeStyle: {
        backgroundColor: "#fff",
        color: "#999",
        boxShadow: "0 0 0 1px #d9d9d9 inset"
      },
      //当前用户
      userByCompanyDefault: null,
      language: localStorage.locale,
      auditsCount: null,
      MODERATED,
      //指南
      modalConfig: {
        visible: false,
        type: "img",
        scrList: []
      },
      bidderListL: []
    };
  },
  computed: {
    auditText() {
      return this.$t("pro.public.header.auditText");
    },
    getLanguage() {
      this.language = this.$i18n.locale;
      return this.language;
    },
    userByCompanys() {
      let userByCompany = this.userByCompany.map(company => {
        return {
          id: company.id,
          value: `${company.company} | ${company.firstName} | ${
            company.lastName
          } | ID#${company.id} | $${Math.floor(company.surplusAmount * 100) /
            100 || 0}`
        };
      });
      //选择当前为默认值
      let item =
        userByCompany.find(item => {
          return item.id == this.userId;
        }) || {};
      this.userByCompanyDefault = item.value || " - ";
      return userByCompany;
    },

    companyInfo() {
      return this.$store.getters.companyInfo;
    },
    userByCompany() {
      return Array.isArray(this.$store.getters.userByCompany)
        ? this.$store.getters.userByCompany
        : [];
    },
    userInfo() {
      return this.$store.getters.userInfo;
    },
    userId() {
      return this.$store.getters.userId;
    },
    theme() {
      return this.companyInfo.setStyle == "white" ? "light" : "dark";
    },
    isMobile() {
      return this.screenWidth <= 768;
    },
    mode() {
      return this.isMobile ? "inline" : "horizontal";
    },
    isAdmin() {
      return this.$store.getters.usIsAdmin;
    },
    showTemplateBelowIcons() {
      return (this.showLanguageSelect || this.showUserList) && this.isMobile;
    },
    adminList() {
      return this.$t("pro.public.header.adminList");
    },
    getHash() {
      return this.$route.path || this.$route.fullPath;
    }
  },
  methods: {
    bidderAd() {
      if (this.bidderListL.length > 0) return;
      this.bidderListL = [
        {
          key: "/bidder/campaigns",
          to: "/bidder/campaigns",
          text: "pro.public.header.Campaigns"
        },
        {
          key: "/bidder/filterlist",
          to: "/bidder/filterlist",
          text: "pro.public.header.FilterList"
        },
        {
          key: "/bidder/creativelibrary",
          to: "/bidder/creativelibrary",
          text: "pro.Library.LibraryWarehouse"
        }
      ];
    },
    //图片重新加载
    againLoad() {
      this.iconLoading = true;
      this.imgLoad = false;
      setTimeout(() => {
        this.imgLoad = true;
      }, 10);
    },
    imgErrored() {
      //显示重新加载按钮
      this.imgLoad = true;
      this.iconLoading = false;
    },
    toNewBidder() {
      //让广告模块改为选中模式
      this.current.pop();
      this.current.unshift("bidder");
      this.bidderListL = [];
      this.$emit("updateFlay", false);
      this.$router.push({ path: "/bidder/campaigns" });
    },
    changeUserByCompany(value, id) {
      this.userByCompanyDefault = value;
      this.$store.commit("changeUserId", id);
      if (this.$route.path.includes("/bidder")) {
        this.$router.push({ path: "/bidder/campaigns" });
      }
      this.reload();
    },
    logout() {
      window.localStorage.clear();
      window.sessionStorage.removeItem("Authorization");
      this.$router.push("/login");

      if (this.companyInfo.setStyle == "dark") {
        updateTheme("white");
      }
    },
    showMenuClick() {
      this.showMenu = !this.showMenu;
    },
    gotItToBidder() {
      this.$emit("updateFlay", false);
      this.$router.push({ path: "/bidder/campaigns" });
    },

    //修改语言
    setLanguage(target) {
      this.$i18n.locale = target;
      this.$store.commit("changeLocale", target);
      //this.reload();
      setTimeout(() => {
        setUserLocale(target).then(res => {});
      }, 1250);
    },
    // 移动端图标的点击事件
    tabToggle(target) {
      if (target == "language") {
        this.showLanguageSelect = !this.showLanguageSelect;
        this.showUserList = false;
      }
      if (target == "user") {
        this.showUserList = !this.showUserList;
        this.showLanguageSelect = false;
      }
    },
    resize() {
      this.screenWidth =
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth;
    }
  },
  watch: {
    getHash(val) {
      this.current.pop();
      this.current.unshift(val);
    }
  },
  mounted() {
    window.addEventListener("resize", this.resize);
  },
  destroyed() {
    window.removeEventListener("resize", this.resize);
  },
  props: {
    newUserFlay: Boolean
  },
  components: {
    modal
  }
};
</script>


<style lang="less">
#app.dark .ant-select-selection-selected-value {
  color: #fff;
}

.iconfont {
  font-size: 24px;
}

.header-top-l {
  height: 75px;
  .logo {
    height: 100%;
  }
  .corp {
    position: relative;
    div.flex-align-items {
      color: #f2784b;
      font-size: 2.16rem;
      img {
        height: 2.8332222222rem;
        max-height: 40px;
        margin-right: 5px;
      }
    }
    a {
      position: absolute;
      top: 0;
      left: 0;
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}

.header-top-r {
  /* .ant-select-selection:focus {
          box-shadow: none;
        } */
  .ant-select-selection {
    border-top: none;
    border-left: none;
    border-right: none;
  }
  > a {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    text-align: center;
    // background-color: #1890ff;
    // color: #fff;
    > i {
      display: inline-block;
      margin: 0 auto;
    }
  }
  a:not(:last-child) {
    margin-right: 2rem;
  }
}

.select-user {
  width: 350px;
  margin-right: 3rem;
}

@media screen and (max-width: 992px) {
  .select-user {
    // width: 300px;
    margin-right: 1rem;
  }
}

@media screen and (max-width: 768px) {
  .select-user {
    width: 100%;
  }
}

.header-menu {
  font-size: 14px;

  > ul {
    margin-bottom: 0;

    > li {
      > div,
      > a {
        text-transform: uppercase;
      }
    }
  }
}

@media screen and (min-width: 769px) {
  .header-menu {
    height: 50px;
    width: 100%;
    > ul {
      height: 100%;
      > li {
        // display: flex;
        height: 100%;
        margin-top: 0 !important;
        > a {
          height: 100%;
        }
        > div {
          border-bottom: none;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .header-top {
    display: block;
  }

  .header-top-l {
    justify-content: space-between;
    .ant-btn {
      padding: 0;
      border: none;
    }
  }

  .header-menu {
    // background: #fff;
    > ul {
      &:not(:last-child) > li {
        border-bottom: 1px solid #f0f0f0;
      }
      > li {
        > a {
          padding-left: 0;
          padding-right: 0;
        }
      }
    }
  }

  nav.header-menu.flex-between {
    display: block;
  }
}

@media screen and (max-width: 768px) {
  .header-top-r {
    display: block;
    border-bottom: none;
    padding: 0;
    > div {
      height: 40px;
      // padding-left: 20px;
      // padding-right: 20px;
      border-bottom: 1px solid #f0f0f0;
      &.no-border {
        border-bottom: none;
      }
      &.template-below-icons {
        height: auto;
        // background-color: #d8e6df;
        padding-top: 5px;
        padding-bottom: 5px;
        > div {
          height: 40px;
        }
      }
    }

    .select-user {
      margin-right: 0;
      width: 100%;
      display: flex;
      align-items: center;
      > label {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }
    .header-tools {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 1em;
      &:hover {
        // background-color: #e6f7ff;
      }
      > a {
        margin-right: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      > a:hover,
      > a:active,
      > a.keep-bgcolor {
        background-color: #d8e6df;
      }
    }
  }
}

.select-user {
  position: relative;
}

.select-user-box {
  width: 100%;
}

@media screen and (min-width: 769px) {
  .select-user-box {
    position: absolute;
    left: 0;
    top: 43px;
  }
}

.mobile-language-select {
  label {
    flex: 1;
    height: 100%;
    line-height: 40px;
    text-align: center;
    box-sizing: border-box;
    position: relative;
    cursor: pointer;

    &.selected,
    &:hover {
      //border-bottom: 1px solid  @primary-color;
      background-color: @primary-color;
      color: #fff;
    }
    &:first-child {
      border-right: 1px solid #f0f0f0;
    }
    input[type="radio"] {
      visibility: hidden;
      position: absolute;
    }
  }
}

#app.dark {
  .mobile-language-select {
    label {
      /* flex: 1;
              height: 100%;
              line-height: 40px;
              text-align: center;
              box-sizing: border-box;
              position: relative;
              cursor: pointer; */

      &.selected,
      &:hover {
        background-color: #666;
      }
      /* &:first-child {
                border-right: 1px solid #f0f0f0;
              }
              input[type="radio"] {
                visibility: hidden;
                position: absolute;
              } */
    }
  }
}

.mobile-profile-list {
  li {
    height: 40px;
    a {
      display: block;
      line-height: 40px;
      padding-left: 40px;
      padding-right: 20px;
    }
  }
}

.dropdown-text {
  padding-left: 10px;
}

.template-below-icons {
  background-color: #d8e6df;
}
</style>
